import { useEffect, useMemo, useRef, useState } from "react";
import { listRole, delRole, exportRole, updateRole, addRole, findMaxSort, apiRoleDisable, apiRoleEnable } from '@/api/system/role'

import SearchForm from "../../../components/searchForm";
import { Table, Divider, Button, message, Modal, Form, Flex, Space, Typography, Avatar, Badge, Tag } from "antd";
import { keepPreviousData, useQueries, useQuery } from "@tanstack/react-query";
import { ModalForm, ProForm, ProFormText, ProFormTextArea } from "@ant-design/pro-components";
import { PlusOutlined, ExclamationCircleFilled, CaretRightOutlined, CaretDownOutlined } from '@ant-design/icons';
import { SvgIcon } from "@/components/icon";
import { useThemeToken } from "@/theme/hooks";
import RoleForm from "./modules/roleForm";
import { useDictionary } from "@/hooks";
import DisplayLabel from "@/components/displayLabel";
import { download, parseTime, rangeQueryNormalize } from "@/utils";
import RoleAppModal from "./modules/appModal";
import RoleDetailModal from "./modules/roleDetailModal";


const queryItems = [
  {
    name: 'codeOrName',
    label: '编码或名称',
    type: 'INPUT',
  }
];
//i18n
const RoleIndex = () => {
  useDictionary(['sys_normal_disable']);
  const roleAppModalRef = useRef()
  const roleDetailModalRef = useRef()
  const [queryParam, setQueryParam] = useState({});
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);
  const [page, setPage] = useState({ pageNo: 1, pageSize: 10 });
  const confirm = Modal.confirm;
  const columns = [
    {
      title: '角色名',
      dataIndex: 'roleName',
      ellipsis: true,
      render: (text, record) => {
        return <Tag color="blue">{text}</Tag>
      }
    },
    {
      title: '角色编码',
      dataIndex: 'roleKey',
      ellipsis: true,
    },
    {
      title: '备注',
      minWidth: '10%',
      dataIndex: 'remark'
    },
    {
      title: '角色状态',
      dataIndex: 'status',
      align: 'center',
      minWidth: 100,
      render: (text) => (<Badge status={text == '0' ? 'processing' : 'error'} text={<DisplayLabel value={text} type="sys_normal_disable" />} />)
    },
    {
      title: '操作',
      key: 'action',
      width: '280px',
      render: (_, record) => (
        <>
          <a onClick={() => roleAppModalRef.current.showModal(record.id)}>权限管理</a>
          <Divider type="vertical" />
          <a onClick={() => roleDetailModalRef.current.showModal(record.id)}>关联用户</a>
          <Divider type="vertical" />

          <ModalForm
            trigger={<a>修改</a>}
            title={`修改角色`}
            modalProps={{ destroyOnClose: true }}
            onFinish={saveData}
            initialValues={{
              ...record
            }}
            grid={true}
          >
            <RoleForm roleId={record.id} />
          </ModalForm>
          <Divider type="vertical" />
          <a onClick={() => { deleteConfirm(record) }}>删除</a>
        </>
      ),
    },
  ];

  const { data: tableData, isFetching, refetch } = useQuery({
    queryKey: ['page-role-listRole', queryParam, page],
    queryFn: () => {
      return listRole({
        pageNum: page.pageNo,
        pageSize: page.pageSize,
        ...rangeQueryNormalize(queryParam)
      }).then((res) => {
        return res.data || {}
      })
    },
    staleTime: 0,
    placeholderData: keepPreviousData,
  })

  const onSelectChange = (selectedRowKeys, selectedRows) => {
    setSelectedRowKeys(selectedRowKeys)
    setSelectedRows(selectedRows)
  }
  const saveData = (values) => {
    if (values.id) {
      return updateRole(values).then(() => {
        refetch()
        message.success('修改成功')
        return true
      })
    } else {
      return addRole(values).then(() => {
        refetch()
        message.success('新增成功')
        return true
      })
    }
  }

  const deleteConfirm = (row) => {
    const ids = row.id || selectedRowKeys
    const roleNames = row.roleName || selectedRows.map(d => d.roleName)
    confirm({
      title: '确认删除所选中数据?',
      icon: <ExclamationCircleFilled />,
      content: '当前选中编号为' + roleNames + '的数据',
      autoFocusButton: null,
      onOk() {
        return delRole(ids)
          .then(() => {
            onSelectChange([], [])
            refetch()
            message.success('删除成功')
          })
      },
      onCancel() { },
    });
  };

  const exportConfirm = () => {
    confirm({
      title: '是否确认导出?',
      content: '此操作将导出当前条件下所有数据而非选中数据',
      autoFocusButton: null,
      onOk() {
        return exportRole({
          pageNum: page.pageNo,
          pageSize: page.pageSize,
          ...queryParam,
        })
          .then(response => {
            download(response.msg)
            message.success('导出成功')
          })
      },
      onCancel() { },
    });
  }

  const handleEnable = () => {
    apiRoleEnable({ ids: selectedRowKeys.join(',') }).then((res) => {
      refetch()
    })
  }
  const handleDisable = () => {
    apiRoleDisable({ ids: selectedRowKeys.join(',') }).then((res) => {
      refetch()
    })
  }

  return (
    <Flex vertical={true} className="searchTableWrapper">
      <div className="searchTableHeader">角色管理</div>
      <SearchForm
        onSearch={(values) => setQueryParam({ ...values })}
        items={queryItems}
        searchContent="查询"
        buttons={<>

          <ModalForm
            trigger={<Button icon={<PlusOutlined />} type="primary">新增</Button>}
            title="添加角色"
            modalProps={{ destroyOnClose: true }}
            onFinish={saveData}
            grid={true}
            request={() => {
              return findMaxSort().then(res => {
                return { status: '0', sort: res?.data }
              })
            }}
          >
            <RoleForm />
          </ModalForm>
          {!!selectedRowKeys.length && <>
            <Button type="primary" onClick={handleEnable}>启用</Button>
            <Button type="primary" onClick={handleDisable}>停用</Button>
            <Button className="ml-2" danger onClick={deleteConfirm}>批量删除</Button>
          </>}

          <Button className="ml-2" onClick={exportConfirm}>导出</Button>
        </>}
      />
      <Table
        rowSelection={{ type: 'checkbox', selectedRowKeys: selectedRowKeys, onChange: onSelectChange }}
        columns={columns}
        rowKey={(record) => record.id}
        loading={isFetching}
        dataSource={tableData?.list}
        pagination={{
          current: page.pageNo,
          pageSize: page.pageSize,
          total: tableData?.total,
          onChange: (pageNo, pageSize) => {
            setPage({ pageNo, pageSize })
          }
        }}
      />

      <RoleAppModal ref={roleAppModalRef}></RoleAppModal>
      <RoleDetailModal ref={roleDetailModalRef}></RoleDetailModal>
    </Flex >
  );
};


export default RoleIndex;
